package net.cardgame.oraclecard.common;

import jp.jma.oraclecard.R;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.ImageView;

public class ImageClickable extends ImageView {
	private String path;
	boolean loadding = false;

	public ImageClickable(Context context) {
		super(context);
	}

	public ImageClickable(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public ImageClickable(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
	}

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.obj == null) {
				ImageClickable.this
						.setImageResource(R.drawable.image_not_found);
				return;
			}
			ImageClickable.this.setImageDrawable((Drawable) msg.obj);
			loadding = false;
		};
	};

	public void loadImage(String path) {
		this.path = path;
		if (path != null) {
			new ThreadLoadImage(mHandler, path, this, 1, true).start();
		}
	}

	public void setPath(String path) {
		this.path = path;
	}

	private void reLoadImage() {
		if (path != null) {
			new ThreadLoadImage(mHandler, path, this, 1, true).start();
		}
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (isEnabled() && isClickable())
			switch (event.getAction() & MotionEvent.ACTION_MASK) {
			case MotionEvent.ACTION_DOWN:
				setColorFilter(Color.parseColor("#ee0467FB"),
						PorterDuff.Mode.MULTIPLY);
				break;
			case MotionEvent.ACTION_UP:
				setColorFilter(null);
				break;
			case MotionEvent.ACTION_CANCEL:
				setColorFilter(null);
				break;
			default:
				break;
			}
		return super.onTouchEvent(event);
	}

	@Override
	protected void onDraw(Canvas canvas) {
		// TODO Auto-generated method stub
		BitmapDrawable drawable = (BitmapDrawable) getDrawable();
		if (drawable != null) {
			Bitmap bitmap = drawable.getBitmap();
			if (!bitmap.isRecycled()) {
				super.onDraw(canvas);
			} else {
				if (!loadding) {
					loadding = true;
					reLoadImage();
				}
			}
		}
	}

}
